import random
import re


class Ai:
  """
  骰子
  买地
  建房子
  卖地
  """
  def __init__(self, player):
    self.player = player
    self.likeBuyBuild = random.randint(0, 2)
    """喜欢买建筑偏好：0、不喜欢；1、混沌；2、喜欢"""

  def JudgeBuyMap(self, mapCost):
    if self.likeBuyBuild == 0:
      return True
    rnd = random.random()
    if rnd < 0.5:
      return True
    return self.player.money > mapCost + 2000

  def JudgeBuild(self, buildCost):
    if self.likeBuyBuild == 0:
      return self.player.money > buildCost + 4000
    rnd = random.random()
    if rnd < 0.5:
      return self.player.money > buildCost + 4000
    return True

  def DiYa(self, flowPath):
    print('DiYa')
    allMap = self.player.GetAllProperty()
    if not allMap:
      # 没有地产了
      self.player.msgBoxLeftBtn.Click()
      return
    for _map in allMap:
      if not _map.mortgage and _map.buildNumber['house'] == 0 and _map.buildNumber['hotel'] == 0:
        _map.panel.childPanel['diYaBtn'].Click()
        self.player.msgBoxRightBtn.Click()
        return
    rnd = random.random()
    # 卖一个房子的地盘房子或空地
    if self.likeBuyBuild == 0 or rnd < 0.5:
      # 不喜欢房子，卖房子
      for _map in allMap:
        if _map.buildNumber['house'] == 1:
          _map.panel.childPanel['house0'].Click()
          self.player.msgBoxRightBtn.Click()
          return
    # 喜欢房子，卖空地
    for _map in allMap:
      if _map.mortgage and _map.buildNumber['house'] == 0 and _map.buildNumber['hotel'] == 0:
        _map.panel.childPanel['sellBtn'].Click()
        self.player.msgBoxRightBtn.Click()
        return
    # 卖房子
    for _map in allMap:
      if _map.buildNumber['house'] > 0:
        _map.panel.childPanel['house0'].Click()
        self.player.msgBoxRightBtn.Click()
        return
    # 卖房子
    for _map in allMap:
      if _map.buildNumber['hotel'] > 0:
        _map.panel.childPanel['hotel'].Click()
        self.player.msgBoxRightBtn.Click()
        return

  def Op(self, flowPath):
    if self.player.msgPanel.visible:
      # 需要做选项
      # 1、判断需不需要买房子
      if flowPath.nowFlowPathName == 'Buy':
        print('ai Buy')
        if self.JudgeBuyMap(flowPath.nowMap.cost):
          self.player.msgBoxRightBtn.Click()
        else:
          self.player.msgBoxLeftBtn.Click()
      elif flowPath.nowFlowPathName == 'Build':
        print('ai Build')
        if self.JudgeBuild(flowPath.nowMap.buildCostConfig['house']):
          self.player.msgBoxRightBtn.Click()
        else:
          self.player.msgBoxLeftBtn.Click()
      elif flowPath.nowFlowPathName == 'BuyBack':
        print('ai BuyBack')
        if self.JudgeBuyMap(flowPath.nowMap.cost * 0.6):
          self.player.msgBoxRightBtn.Click()
        else:
          self.player.msgBoxLeftBtn.Click()
      else:
        # 应该是抵押了吧？
        print('ai DiYa')
        self.DiYa(flowPath)
      return
    if self.player.canRollBtn.visible:
      # 投骰子
      self.player.canRollBtn.Click()

